
#include "ksstr.h"

#pragma warning( disable : 4290 )


namespace ksstr
{



bool TextItemsHolder::IsLineName(std::string& name, const std::string& line)
{
	if(line.empty()) return false;
	if(line.length() < 8) return false;
	if( line[0] != '<' ) return false;
	if( line[line.length()-1] != '>' ) return false;

	int posEq = -1;
	name.clear();
	for(size_t c=0; c<line.length(); c++)
	{
		const char curr = line[c];
		if( curr == '=' )
		{
			posEq = (int)c;
			break;
		}
	}

	if(posEq == -1) return false;

	name = line.substr( posEq+1 ,  line.length()-posEq-2 );

	// check name  ??



	return true;
}

 


void TextItemsHolder::WriteToText(std::string& dest) const
{
	dest += "\n";

	for(int c=0; c<(int)m_items.size(); c++)
	{

		dest += "\n<text=";
		dest += m_items[c].m_name;
		dest +=">\n";

		dest += m_items[c].m_text;

		dest += "\n</text>\n\n";
	}
}



bool TextItemsHolder::SaveToFileW(const std::wstring& filename) const
{
	std::string text;
	WriteToText(text);
	return ksstr::saveStrToFileW( text, filename.c_str() );
}
 

bool TextItemsHolder::ReadFromText(const std::string& src)
{
	std::vector<std::string> lines;
	ksstr::splitLines(lines, src);

	std::string textname;
	std::string text;

	bool inText = false;

	for(size_t c=0; c<lines.size(); c++)
	{
		const std::string& line = lines.at(c);

		if(line.length() == 0)
		{
			continue;
		}


		if( IsLineName(textname, line) )
		{
			inText = true;
			continue;

		}

		if(line == "</text>")
		{
			text_item_s ti(textname, text);
			m_items.push_back( ti );
			textname = "";
			text = "";
			inText = false;
			continue;
		}


		// add
		if( inText )
		{

			text += lines[c];
			text += "\n";

		}
		
	}


	return true;
}

 
bool TextItemsHolder::LoadFromFileW(const std::wstring& filename)
{
	std::string text;
	if( !ksstr::loadStrFromFileW( text , filename.c_str() ) )
	{
		return false;
	}

	return ReadFromText(text);
}



text_item_s& TextItemsHolder::Add(
								const std::string& name, const std::string& text)
{
	text_item_s ti( name , text );
	m_items.push_back( ti );
	return m_items.at( m_items.size()-1 );
}


size_t  TextItemsHolder::SearchText(const std::string& text_name) const
{
	for( size_t c=0; c<m_items.size(); c++ )
	{
		const text_item_s& itm = m_items.at(c);
		if( itm.m_name == text_name )
		{
			return c;
		}
	}

	return  0-1;
}

  

void TextItemsHolder::GetTextAt(std::string& name, std::string& text, 
								const size_t index) const   throw(std::runtime_error)
{
	if( index >= m_items.size() )
	{
		throw std::runtime_error("bad index");
	}

	const text_item_s& itm = m_items.at( index );
	name = itm.m_name;
	text = itm.m_text;

}

}

